import WebSocket, { WebSocketServer } from 'ws';

const port =7008

// 创建WebSocket服务器，监听端口8080
const wss = new WebSocketServer({ port: port });

wss.on('connection', (ws) => {
    console.log('客户端已连接');

    // 发送欢迎消息给客户端
    ws.send(JSON.stringify({ message: '欢迎连接到WebSocket服务器' }));

    // 监听客户端发送的消息
    ws.on('message', (message) => {
        console.log(`收到消息: ${message}`);

        // 处理消息并发送响应
        ws.send(JSON.stringify({ message: '服务器已收到消息' }));
        console.log('接收到的数据类型',typeof message);
        broadcast(message.toString() );
    });

    // 监听客户端断开连接
    ws.on('close', () => {
        console.log('客户端已断开连接');
    });

    // 监听错误
    ws.on('error', (error) => {
        console.error(`WebSocket错误: ${error}`);
    });
});

console.log(`WebSocket服务器已启动，监听端口${port}`);


function broadcast(data) {
    wss.clients.forEach((client) => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(data);
        }
    });
}
export { broadcast };